import { cadAppErrorLog, S3Inst, StringUtils } from '@amcax/base';
import { InboxOutlined } from '@ant-design/icons';
import { PickableCommandForm } from '@app-cad/common/components/command-form/pickable';
import { loadEmit } from '@app-cad/common/events/CoreEvent';
import { MessageTip } from '@app-cad/common/utils/MessageTip';
import { documentV2 } from '@app-cad/environments/nextmesh/domain';
import { ctx2, environmentManager } from '@app-cad/module';
import { wsApi } from '@app-cad/server';
import { RJSFSchema } from '@rjsf/utils';
import type { UploadProps } from 'antd';
import { Upload } from 'antd';
import i18n from 'i18next';

const { Dragger } = Upload;

interface ImportDialogProps {
  title: string;
  onClose: () => void;
}

export function ImportDialog({ title, onClose }: ImportDialogProps) {
  let fileType = '';

  const uploadFile = (options) => {
    loadEmit(true);
    const { file, onSuccess, onProgress } = options;
    const fileTypeIndex = file.name.split('.').length - 1;
    fileType = file.name.split('.')[fileTypeIndex];
    const ossfile = StringUtils.randomString(10) + '.' + fileType;
    S3Inst.uploadFile(
      'cad',
      ossfile,
      file,
      (progress: { loaded: number; total: number }) => {
        const percentage = Math.floor((progress.loaded * 100) / progress.total);
        onProgress({ percent: percentage }, file);
      },
      async (data: { bucket: string; path: string }) => {
        const bucket = data.bucket;
        const path = data.path;
        await doRender('s3://' + bucket + path, fileType);
        onSuccess({ name: path, status: 'done', file });
      },
    );
  };

  // 宽度为400px
  const props: UploadProps = {
    name: 'file',
    multiple: true,
    accept: `.dxf,.brep,.step,.stp${environmentManager.activatedEnv.id === 'Nextmesh' ? ',.txt,.tecplot' : ''}`,
    onChange(info) {
      if (info.file.status === 'error') {
        MessageTip.error(`${info.file.name} 文件上传失败`);
      }
    },
    customRequest: uploadFile,
  };

  const doRender = async (filepath: string, fileType: string) => {
    try {
      const params = {
        t: filepath,
      };
      if (fileType === 'txt' || fileType === 'tecplot') {
        await documentV2.import(filepath);
      } else {
        await wsApi.importModel(params);
      }
      ctx2.viewer.fitObjectView();
      onClose();
    } catch (e) {
      cadAppErrorLog(e);
    } finally {
      loadEmit(false);
    }
  };

  const UploadDragger = () => {
    return (
      <Dragger {...props}>
        <p className='ant-upload-drag-icon'>
          <InboxOutlined />
        </p>
        <p className='ant-upload-text'>{i18n.t('uploader.drag_text')}</p>
        <p className='ant-upload-hint'>
          支持上传文件类型：.dxf,.brep,.step,.stp,.txt,.tecplot
        </p>
      </Dragger>
    );
  };

  const schema: RJSFSchema = {
    type: 'object',
    properties: {
      upload: {
        type: 'string',
      },
    },
  };

  return (
    <PickableCommandForm
      title={title}
      onClose={onClose}
      schema={schema}
      extraUiSchema={{
        upload: {
          'ui:widget': UploadDragger,
        },
      }}
      showSubmit={false}
      showCancel={false}
    />
  );
}
